package com.example.venue_reservation_service.dcpint.util;

/*import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;*/

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.Key;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class IfsDcpIntUtils {

	// 向量
	private final static String iv = "01234567";
	// 加解密统一使用的编码方式
	private final static String encoding = "utf-8";
//	private final static String pk="ll.ecjtull.ecjtull.ecjtu";//lltest
	private final static String pk="08192ec57d80193b9fa4b9a0";//lltest

	private static String PATH = "http://dcpint.ecjtu.edu.cn/unis/IfsDcpIntPortalServlet";
	private static URL url;
    
	
	
    static {
        try {
          url = new URL(PATH);
        } catch (MalformedURLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    
	public static String desEncode(String plainText) throws Exception {
			Key deskey = null;
			DESedeKeySpec spec = new DESedeKeySpec(pk.getBytes());
			SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
			deskey = keyfactory.generateSecret(spec);

			Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
			IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
			byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
			return Bytes2HexString(encryptData);
	}
	
	public static String desDecode(String encryptText) throws Exception {
		Key deskey = null;
		DESedeKeySpec spec = new DESedeKeySpec(pk.getBytes());
		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
		deskey = keyfactory.generateSecret(spec);
		Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
		IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
		cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
//		BASE64Decoder mi = new BASE64Decoder();
//		System.out.println(encryptText);
		byte[] decryptData = cipher.doFinal(hexStringToBytes(encryptText));

		return new String(decryptData, encoding);
	}
	
	private static String Bytes2HexString(byte[] b) {
		String ret = "";
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			ret += hex.toUpperCase();
		}
		return ret;
	}
	
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}
	
	
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
	
	
	
	
	/*public static String httpGetRequest(String url) {
		// 定义HttpClient
		HttpClient client = new DefaultHttpClient();
		// 实例化HTTP方法
		HttpGet request = new HttpGet();

		HttpResponse response;
		String jsonStr = "";
		try {
			request.setURI(new URI(url));
			response = client.execute(request);
			System.out.println(response.getEntity().getContent().toString());
			jsonStr = EntityUtils.toString(response.getEntity());
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonStr;
	}*/
	
	public static String httpPostRequest(Map<String, String> params) {
		    StringBuffer stringBuffer = new StringBuffer();

		    if (params != null && !params.isEmpty()) {
		      for (Map.Entry<String, String> entry : params.entrySet()) {
		        try {
		          stringBuffer
		              .append(entry.getKey())
		              .append("=")
		              .append(URLEncoder.encode(entry.getValue(), encoding))
		              .append("&");

		        } catch (UnsupportedEncodingException e) {
		          e.printStackTrace();
		        }
		      }
		      // 删掉最后一个 & 字符
		      stringBuffer.deleteCharAt(stringBuffer.length() - 1);
		//      System.out.println("-->>" + stringBuffer.toString());

		      try {
		        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		        httpURLConnection.setConnectTimeout(3000);
		        httpURLConnection.setDoInput(true);// 从服务器获取数据
		        httpURLConnection.setDoOutput(true);// 向服务器写入数据

		        // 获得上传信息的字节大小及长度
		        byte[] mydata = stringBuffer.toString().getBytes();
		        // 设置请求体的类型
		        httpURLConnection.setRequestProperty("Content-Type",
		            "application/x-www-form-urlencoded");
		        httpURLConnection.setRequestProperty("Content-Lenth",
		            String.valueOf(mydata.length));

		        // 获得输出流，向服务器输出数据
		        OutputStream outputStream = (OutputStream) httpURLConnection.getOutputStream();
		        outputStream.write(mydata);

		        // 获得服务器响应的结果和状态码
		        int responseCode = httpURLConnection.getResponseCode();
		        if (responseCode == 200) {
		          // 获得输入流，从服务器端获得数据
		          InputStream inputStream = (InputStream) httpURLConnection
		              .getInputStream();
		          return (changeInputStream(inputStream));
		        }

		      } catch (IOException e) {
		        e.printStackTrace();
		      }
		    }
		    return "-1";
		  }

		  /*
		   * // 把从输入流InputStream按指定编码格式encode变成字符串String
		   */
		  public static String changeInputStream(InputStream inputStream) {
		    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		    byte[] data = new byte[1024];
		    int len = 0;
		    String result = "";
		    if (inputStream != null) {
		      try {
		        while ((len = inputStream.read(data)) != -1) {
		          byteArrayOutputStream.write(data, 0, len);
		        }
		        result = new String(byteArrayOutputStream.toByteArray(), encoding);
		      } catch (IOException e) {
		        e.printStackTrace();
		      }
		    }
		    return result;
	  }
		  
		  
		  
		 
		  
		  
}
